package com.yulamg.core.filter;

import com.yulamg.core.respository.UserRespository;
import com.yulamg.core.user.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class BasicAuthecationFilter extends OncePerRequestFilter {

    @Autowired
    private UserRespository userRespository;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        String authorization = httpServletRequest.getHeader("Authorization");

        if(StringUtils.isNoneBlank(authorization)){


            String token = StringUtils.substringAfter(authorization,"Basic ");
            String tokens = new String(Base64Utils.decodeFromString(token));
            String[] item = StringUtils.splitByWholeSeparator(tokens,":");
            String username = item[0];
            String password = item[1];
            User jojo = userRespository.findByUsername("222");
            if(jojo==null){
                httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
                httpServletResponse.getWriter().flush();
                return;
            }else{
                if(StringUtils.equals(username,jojo.getUsername())&&StringUtils.equals(password,jojo.getPassword())){
                    httpServletRequest.setAttribute("user",jojo);
                   filterChain.doFilter(httpServletRequest,httpServletResponse);
                }else{
                    httpServletResponse.getWriter().write(HttpStatus.UNAUTHORIZED.value());
                    httpServletResponse.getWriter().flush();
                    return;
                }
            }

        }else{
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }



    }
}
